import Vue from 'vue';
import { isFunction, isString } from '@/vuego/utils/isX';

import VToast from './v-toast';

const MessageConstructor = Vue.extend(VToast);
const instances = [];

let instance;
let seed = 1;
let TOSAT_ZINDEX = 2100;

const Toast = (options) => {
  if (Vue.prototype.$isServer) return;
  options = options || {};
  if (isString(options)) {
    options = {
      message: options,
    };
  }
  const userOnClose = options.onClose;
  const id = `toast_${seed += 1}`;

  options.onClose = () => {
    Toast.close(id, userOnClose);
  };
  instance = new MessageConstructor({
    data: options,
  });
  instance.id = id;

  instance.vm = instance.$mount();
  document.body.appendChild(instance.vm.$el);
  instance.vm.visible = true;
  instance.dom = instance.vm.$el;
  instance.dom.style.zIndex = TOSAT_ZINDEX;
  instances.push(instance);

  TOSAT_ZINDEX += 1;
};

['success', 'warning', 'info', 'error'].forEach((type) => {
  Toast[type] = (options) => {
    if (isString(options)) {
      options = {
        message: options,
      };
    }
    options.type = type;
    return Toast(options);
  };
});

Toast.close = function close(id, userOnClose) {
  for (let i = 0, len = instances.length; i < len; i += 1) {
    if (id === instances[i].id) {
      if (isFunction(userOnClose)) {
        userOnClose(instances[i]);
      }
      instances.splice(i, 1);
      break;
    }
  }
};

Toast.closeAll = function closeAll() {
  for (let i = instances.length - 1; i >= 0; i -= 1) {
    instances[i].close();
  }
};

export default Toast;
